﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using System.Linq;
using System;


static class SpriteExtension
{
    static public Sprite ToSprite(this Texture2D texture)
    {
        return Sprite.Create(texture, new Rect(0, 0, texture.width, texture.height), new Vector2(0.5f, 0.5f));
    }
    static public Sprite[,] CutPicture(Texture2D texture, Vector2Int XY)
    {
        Sprite[,] sprites = new Sprite[XY.x, XY.y];
        int perX = texture.width / XY.x;
        int perY = texture.height / XY.y;

        for (int x = 0; x < XY.x; x++)
        {
            for (int y = 0; y < XY.y; y++)
            {
                try
                {
                    var rect = new Rect(perX * x, perY * (XY.y - 1 - y), perX, perY); //图片切的不对
                    sprites[x, y] = Sprite.Create(texture, rect, new Vector2(0.5f, 0.5f));
                    sprites[x, y].name = x.ToString() + "," + y.ToString();
                }

                catch
                {
                    Debug.LogError("错误的越界，检查图片");
                }
            }
        }
        return sprites;
    }

    static public T[] FindObjChildrens<T>(GameObject Obj) where T : MonoBehaviour
    {
        var g = from p in Obj.GetComponentsInChildren<T>()
                orderby p.name ascending //正向排序
                select p;
        return g.ToArray();
    }
}

